package com.xixilala.zh_ad_style

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import androidx.annotation.DrawableRes

/***
 * 呱呱卡
 * 1.首先画背景
 * 2.再画手势路径和上层图不重合的
 */
class ScratchCardView : View {
    private var scratchBitmap : Bitmap?= null
    private val paint:Paint = Paint().apply {
        style = Paint.Style.STROKE
        strokeCap = Paint.Cap.ROUND
        color = Color.BLUE
        strokeWidth  = 100F
    }
    private val path = Path()
    constructor(context: Context?) : super(context)
    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    )

    fun setScratchableImage(@DrawableRes res:Int) {
        scratchBitmap = BitmapFactory.decodeResource(resources, res)
        invalidate()
    }

    fun reset() {
        path.rewind()
        invalidate()
    }

    @SuppressLint("DrawAllocation")
    override fun onDraw(canvas: Canvas?) {

        canvas?.let {
            setLayerType(LAYER_TYPE_SOFTWARE,null)
            val layerId = canvas.saveLayer(
                0F,
                0F,
                width.toFloat(),
                height.toFloat(),
                paint,
                Canvas.ALL_SAVE_FLAG
            )

            scratchBitmap?.let { canvas.drawBitmap(it,0F,0F,paint) }
            paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.XOR)
            canvas.drawPath(path,paint)
            paint.xfermode = null

            canvas.restoreToCount(layerId)
        }



    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        Logs.d("开始触摸---${event?.action}")
        event?.let {
            when(it.action) {
                MotionEvent.ACTION_DOWN->{
                    path.moveTo(it.x,it.y)
                }
                MotionEvent.ACTION_MOVE->{
                    path.lineTo(event.x,event.y)
                    invalidate()
                }
                MotionEvent.ACTION_UP->{
//                    path.close()
                }
            }
        }

        return true
    }


}